package com.example.ysy_hooktest;

import android.app.Instrumentation;
import android.content.Context;
import android.util.Log;

import java.lang.reflect.Field;

public class HookHelper {

    public static void init(Context context){
        try {
            Field mMainThreadField = ApkUtil.getField(context, "mMainThread");
            Log.e("TAG", "init: "+mMainThreadField );
            Object mMainThread = mMainThreadField.get(context);
            Field mInstrumentationField = ApkUtil.getField(mMainThread, "mInstrumentation");
            Object mInstrumentation = mInstrumentationField.get(mMainThread);
//            Field mThread = ApkUtil.getField(mInstrumentation, "mThread");
            InstrumentationProxy instrumentationProxy = new InstrumentationProxy((Instrumentation) mInstrumentation,
                    context.getPackageManager());
//            Field mThread1 = ApkUtil.getField(instrumentationProxy, "mThread");
//            mThread1.set(instrumentationProxy,mThread);
            mInstrumentationField.set(mMainThread,instrumentationProxy);
        } catch ( Exception e) {
            e.printStackTrace();
        }

    }

    public static void init1(Context context){
        try {
            try {
                //获取ActivityThread类
                Class<?> activityThreadClazz = Class.forName("android.app.ActivityThread");
                //获取其中的静态变量 sCurrentActivityThread 它对应着当前的ActivityThread对象
                Field activityThreadField = activityThreadClazz.getDeclaredField("sCurrentActivityThread");
                activityThreadField.setAccessible(true);
                //获取到 sCurrentActivityThread 对象
                Object currentActivityThread = activityThreadField.get(null);
                Field mInstrumentationField = activityThreadClazz.getDeclaredField("mInstrumentation");
                mInstrumentationField.setAccessible(true);
                Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
                //执行替换操作
                mInstrumentationField.set(activityThreadField,new InstrumentationProxy((Instrumentation) mInstrumentation,
                        context.getPackageManager()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch ( Exception e) {
            e.printStackTrace();
        }

    }
}
